
package com.yuan.unit;

import org.apache.http.HttpHost;
import org.apache.http.HttpMessage;
import org.apache.http.HttpResponse;
import org.apache.http.HttpVersion;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.params.ConnRoutePNames;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.params.CoreProtocolPNames;
import org.apache.http.util.EntityUtils;

import android.annotation.SuppressLint;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.text.TextUtils;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.HashMap;

/**
 * HTTP工具类 主要就两个方法 get post
 * 
 * @author YUAN
 */
@SuppressLint("DefaultLocale")
@SuppressWarnings("unused")
public class HttpUtils {

    private final static String TAG = HttpUtils.class.getSimpleName();
    public final static int CONNECT_TIMEOUT = 5000;
    public final static int SOCKET_TIMEOUT = 10000;

    public static String encodeToUtf8(String source) {
        try {
            return URLEncoder.encode(source, "utf-8");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * put [prefix] in front of the returned byte
     * 
     * @param ins
     * @param prefix
     * @param closeStream
     * @return
     * @throws Exception
     */

    /**
     * Get a smart HttpGet obj, one solution for wifi/wap/net
     * 
     * @param context
     * @param url
     * @return
     */
    public final static HttpGet createHttpGet(Context context, String url) {
        ConnectivityManager cm = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo info = cm.getActiveNetworkInfo();
        if (null == info)
            return new HttpGet(url);
        return createHttpGet(context, info, url);
    }

    public final static String getUrlContent(Context context, String url, String encoding)
            throws ClientProtocolException, IOException {
        url = url.replace(" ", "%20");
        BLog.d("yuanwei", "请求网址 = " + url);
        HttpGet request = createHttpGet(context, url);
        HttpClient client = new DefaultHttpClient();
        client.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
        client.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, CONNECT_TIMEOUT);
        client.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, SOCKET_TIMEOUT);
        HttpResponse response = client.execute(request);
        String r = EntityUtils.toString(response.getEntity(), encoding);
        BLog.d("yuanwei", "返回内容 = " + r);
        return r;
    }

    /**
     * Get a smart HttpGet obj, one solution for wifi/wap/net
     * 
     * @param context
     * @param net
     * @param url
     * @return
     */
    private final static HttpGet createHttpGet(Context context, NetworkInfo net, String url) {
        HttpGet httpGet = new HttpGet(url);
        setProxy(httpGet, net);
        return httpGet;
    }

    private final static void setProxy(HttpMessage httpMessage, NetworkInfo net) {

        if (null == net)
            return;

        String extraInfo = getApn(net);
        if (false == TextUtils.isEmpty(extraInfo) && apnProxy.containsKey(extraInfo)) {
            String proxy = apnProxy.get(extraInfo);
            int pos = proxy.indexOf(':');
            String host = proxy.substring(0, pos);
            String port = proxy.substring(pos + 1);
            httpMessage.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY,
                    new HttpHost(host, Integer.valueOf(port)));
        }
    }

    private static HashMap<String, String> apnProxy = new HashMap<String, String>();

    public final static String APN_CMWAP = "cmwap";
    public final static String APN_UNIWAP = "uniwap";
    public final static String APN_3GWAP = "3gwap";
    public final static String APN_CTWAP = "ctwap";
    static {
        apnProxy.put(APN_CMWAP, "10.0.0.172:80");
        apnProxy.put(APN_UNIWAP, "10.0.0.172:80");
        apnProxy.put(APN_3GWAP, "10.0.0.172:80");
        apnProxy.put(APN_CTWAP, "10.0.0.200:80");
    }

    public static String getApn(NetworkInfo ni) {
        String ex = ni.getExtraInfo();
        if (TextUtils.isEmpty(ex))
            return null;

        if (ex.toLowerCase().contains(APN_CMWAP))
            return APN_CMWAP;
        if (ex.toLowerCase().contains(APN_UNIWAP))
            return APN_UNIWAP;
        if (ex.toLowerCase().contains(APN_3GWAP))
            return APN_3GWAP;
        if (ex.toLowerCase().contains(APN_CTWAP))
            return APN_CTWAP;

        return ex;
    }

    public static HashMap<String, String> getApnProxyConfig() {
        return apnProxy;
    }

    public static boolean isProxyApn(String apn) {
        if (apn == null) {
            return false;
        }
        return HttpUtils.APN_3GWAP.equals(apn) || HttpUtils.APN_CMWAP.equals(apn)
                || HttpUtils.APN_CTWAP.equals(apn)
                || HttpUtils.APN_UNIWAP.equals(apn);
    }

    /**
     * Helper function to get net proxy parameters.
     * 
     * @param context Context used to launch the invoked activity.
     */
    public static HttpHost getNetProxy(Context context) {
        HttpHost ret = null;
        ConnectivityManager cm = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo ni = cm.getActiveNetworkInfo();
        if (ni != null) {
            String apn = HttpUtils.getApn(ni);
            if (apn != null) {

                if ("cmwap".equals(apn) || "uniwap".equals(apn) || "3gwap".equals(apn)) {
                    ret = new HttpHost("10.0.0.172", 80);
                } else if ("ctwap".equals(apn)) {
                    ret = new HttpHost("10.0.0.200", 80);
                }
            }
        }
        return ret;
    }
}
